<?php

namespace addons\groupon\library\traits;

use addons\groupon\exception\Exception;
use addons\groupon\model\Goods;
use addons\groupon\model\GoodsSkuPrice;
use addons\groupon\model\OrderItem;
use addons\groupon\model\ScoreGoodsSkuPrice;
use addons\groupon\model\store\TakeLog;
use addons\groupon\model\Store;
use addons\groupon\model\User;
use addons\groupon\model\UserStore;

/**
 * 自提点抽成
 */
trait StoreTake
{
    private $config = [];

    // ------------------读取配置-----------------------
    public function getSystemConfig() {
        if (!$this->config) {
            $this->config = json_decode(\addons\groupon\model\Config::where(['name' => 'store'])->value('value'), true);
        }

        return $this->config;
    }

    public function getConfigPriceType() {
        $this->getSystemConfig();
        return $this->config['store_price_type'] ?? 'pay_price';
    }

    public function getConfigTakeEvent() {
        $this->getSystemConfig();
        return $this->config['store_take_event'] ?? 'payed';
    }

    public function getConfigRefundReduce() {
        $this->getSystemConfig();
        return isset($this->config['store_refund_reduce']) ? intval($this->config['store_refund_reduce']) : 1;
    }
    
    public function getConfigDefaultStoreTake() {
        $this->getSystemConfig();
        $store_take = [
            'take_type' => $this->config['store_take_type'] ?? 'rate',
            'take_money' => $this->config['store_take_money'] ?? 0,
            'take_rate' => $this->config['store_take_rate'] ?? 0,
        ];

        return $store_take;
    }


    // 获取自提点，及自提点用户
    public function getStoreData($item) {
        $store = null;
        $user = null;
        if ($item['store_id']) {
            $store = Store::get($item['store_id']);
        }

        if ($store) {
            $userStore = UserStore::where('store_id', $item['store_id'])->find();
            if ($userStore) {
                $user = User::get($userStore['user_id']);
            }
        }

        if (!$user) {
            return false;
        }

        return [
            'store' => $store,
            'user' => $user
        ];
    }


    // ------------------------计算佣金-------------------
    public function getTakePrice($item) {
        $price_type = $this->getConfigPriceType();
        $amount = round(0, 2);
        switch ($price_type) {
            case 'pay_price':
                $amount = $item['pay_price'];
                break;
            case 'goods_price':
                $amount = round($item['goods_price'] * $item['goods_num'], 2);
                break;
        }
        return $amount;
    }


    public function getTakeData($item) {
        $skuPrice = GoodsSkuPrice::where('goods_id', $item['goods_id'])->where('id', $item['goods_sku_price_id'])->find();

        $store_take = $skuPrice ? json_decode($skuPrice['store_take'], true) : [];
        if (!$store_take) {
            // 使用公共 store_take
            $store_take = $this->getConfigDefaultStoreTake();
        }

        $amount = $this->getTakePrice($item);
        $take_money = 0;
        if ($store_take['take_type'] == 'money') {
            $take_money = round($store_take['take_money'] * $item['goods_num'], 2);
        } else if ($store_take['take_type'] == 'rate') {
            $take_money = round($amount * $store_take['take_rate'] * 0.01, 2);
        }

        return [
            'take_money' => $take_money,
            'store_take' => $store_take,
            'amount' => $amount,
        ];
    }


    // 添加佣金明细
    public function createTakeItem($item) {
        $storeData = $this->getStoreData($item);
        if (!$storeData) {
            // 未找到自提点用户
            return false;
        }

        // 抽成
        $takeData = $this->getTakeData($item);

        if ($takeData['take_money'] > 0) {
            // 添加佣金明细
            $takeLog = new TakeLog();

            $takeLog->order_id = $item['order_id'];
            $takeLog->order_item_id = $item['id'];
            $takeLog->goods_id = $item['goods_id'];
            $takeLog->buyer_id = $item['user_id'];
            $takeLog->user_id = $storeData['user']['id'];
            $takeLog->store_id = $storeData['store']['id'];
            $takeLog->store_take = json_encode($takeData['store_take']);
            $takeLog->take_event = $this->getConfigTakeEvent();
            $takeLog->price_type = $this->getConfigPriceType();
            $takeLog->amount = $takeData['amount'];
            $takeLog->take_money = $takeData['take_money'];
            $takeLog->original_take_money = $takeData['take_money'];
            $takeLog->status = 0;
            $takeLog->save();

            return $takeLog;
        }

        return false;
    }



    // 发放抽成
    public function runTakeMoney($takeLog, $type) {
        // 抽成已到账
        if ($takeLog['status'] !== 0) {
            return false;
        }

        // 判断结算方式
        if ($takeLog['take_event'] != $type && $type !== 'admin') {
            return false;
        }

        $takeLog->status = 1;
        $takeLog->take_time = time();
        $takeLog->save();

        // 增加用户余额
        User::money($takeLog->take_money, $takeLog->user_id, 'take_money', $takeLog->id, '', [
            'id' => $takeLog['id'],
            'order_id' => $takeLog['order_id'],
            'order_item_id' => $takeLog['order_item_id'],
            'goods_id' => $takeLog['goods_id'],
            'buyer_id' => $takeLog['buyer_id'],
            'user_id' => $takeLog['user_id'],
            'store_id' => $takeLog['store_id'],
            'store_take' => $takeLog['store_take'],
            'take_event' => $takeLog['take_event'],
            'price_type' => $takeLog['price_type'],
            'amount' => $takeLog['amount'],
            'take_money' => $takeLog['take_money'],
            'original_take_money' => $takeLog['original_take_money'],
            'take_time' => $takeLog['take_time'],
            'status' => $takeLog['status'],
        ]);

        return true;
    }


    // 退回抽成
    public function backTakeMoney($takeLog, $type) {
        // 不可退回
        if ($takeLog['status'] !== 1) {
            return false;
        }

        if ($type == 'refund' && !$this->getConfigRefundReduce()) {
            // 退款操作，并且退款不退回佣金
            return false;
        }

        $takeLog->status = -1;
        $takeLog->save();

        // 减少用户余额
        User::money(-$takeLog->take_money, $takeLog->user_id, 'take_money_back', $takeLog->id, '', [
            'id' => $takeLog['id'],
            'order_id' => $takeLog['order_id'],
            'order_item_id' => $takeLog['order_item_id'],
            'goods_id' => $takeLog['goods_id'],
            'buyer_id' => $takeLog['buyer_id'],
            'user_id' => $takeLog['user_id'],
            'store_id' => $takeLog['store_id'],
            'store_take' => $takeLog['store_take'],
            'take_event' => $takeLog['take_event'],
            'price_type' => $takeLog['price_type'],
            'amount' => $takeLog['amount'],
            'take_money' => $takeLog['take_money'],
            'original_take_money' => $takeLog['original_take_money'],
            'take_time' => $takeLog['take_time'],
            'status' => $takeLog['status'],
        ]);

        return true;
    }
}
